package com.example.messengerapp.ui

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import com.bumptech.glide.Glide
import com.example.messengerapp.databinding.FragmentFullScreenImageBinding
import com.example.messengerapp.viewmodel.FullScreenImageViewModel


class FullScreenImageFragment : Fragment() {

    private var _binding: FragmentFullScreenImageBinding? = null
    private val binding get() = _binding!!

    private val viewModel: FullScreenImageViewModel by viewModels()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentFullScreenImageBinding.inflate(inflater, container, false).apply {
            lifecycleOwner = viewLifecycleOwner
            viewModel = this@FullScreenImageFragment.viewModel
        }
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val imageUrl = arguments?.getString("imageUrl")
        if (imageUrl != null) {
            viewModel.setImageUrl(imageUrl)
        }

        observeViewModel()
    }

    private fun observeViewModel() {
        viewModel.imageUrl.observe(viewLifecycleOwner, { url ->
            Glide.with(this).load(url).into(binding.imageViewFullScreen)
        })
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}
